package com.aglow.bluetoothspeaker.main.ui.activity;


import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.actions.ibluz.factory.BluzDeviceFactory;
import com.actions.ibluz.factory.IBluzDevice;
import com.actions.ibluz.manager.IBluzManager;
import com.aglow.bluetoothspeaker.R;
import com.aglow.bluetoothspeaker.app.Config;
import com.aglow.bluetoothspeaker.main.base.BaseActivity;
import com.aglow.bluetoothspeaker.main.ui.dialog.PromptDialog;
import com.aglow.bluetoothspeaker.main.ui.dialog.SearchBluetoothDialog;
import com.aglow.bluetoothspeaker.main.ui.view.PullUpDragLayout;
import com.aglow.bluetoothspeaker.model.cache.MusicCache;
import com.aglow.bluetoothspeaker.model.event.BluzManagerReadyEvent;
import com.aglow.bluetoothspeaker.model.event.ConnectedStateChangedEvent;
import com.aglow.bluetoothspeaker.model.event.HomeKeyEvent;
import com.aglow.bluetoothspeaker.presenter.lisnter.NoDoubleClickListener;
import com.aglow.bluetoothspeaker.presenter.receiver.HomeKeyReceiver;
import com.aglow.bluetoothspeaker.utils.BluzDeviceFactoryUtils;
import com.aglow.bluetoothspeaker.utils.BluzDeviceUtils;
import com.aglow.bluetoothspeaker.utils.BluzManagerUtils;
import com.aglow.bluetoothspeaker.utils.DialogFragmentUtils;
import com.aglow.bluetoothspeaker.utils.SpManager;
import com.aglow.bluetoothspeaker.utils.ToastUtil;
import com.aglow.bluetoothspeaker.utils.Utility;
import com.blankj.utilcode.util.SPUtils;
import com.facebook.stetho.common.LogUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Calendar;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Author: chufeng
 * Email: 392044178@qq.com
 * Date: 2018/9/12 11:04
 */
public class MainActivity extends BaseActivity {


    @BindView(R.id.btn_bluetooth)
    ImageButton btnBluetooth;
    @BindView(R.id.btn_clock)
    ImageButton btnClock;
    @BindView(R.id.btn_led)
    ImageButton btnLed;
    @BindView(R.id.ll_button)
    LinearLayout llButton;
    @BindView(R.id.iv_drag)
    ImageView ivDrag;
    @BindView(R.id.iv_title)
    ImageView ivTitle;
    @BindView(R.id.iv_phone)
    ImageView ivPhone;
    @BindView(R.id.iv_bluetooth_state)
    ImageView ivBluetoothState;
    @BindView(R.id.tv_bluetooth_info)
    TextView tvBluetoothInfo;
    @BindView(R.id.pdl_root)
    PullUpDragLayout pdlRoot;
    private static final String DISCONNECT_DIALOG_TAG = "MainActivity.ClosePromptDialog";
    private static final String BLUETOOTH_SEARCH_DIALOG_TAG = "MainActivity.BluetoothDeviceSearchDialog";
    private ObjectAnimator mScaleAnimator;
    private boolean isConnect = false;
    private boolean isUserDisconnect = false;
    private BluzDeviceUtils bluzDeviceUtils = BluzDeviceUtils.getInstance();
    private BluzManagerUtils mBluzManagerUtils = BluzManagerUtils.getInstance();
//    private BluzDeviceFactoryUtils mBluzFactoryUtils = BluzDeviceFactoryUtils.getInstance();
    private BluetoothDevice connectedDevice;
    private Activity mContext;
    private SearchBluetoothDialog mSearchDialog;
    private PromptDialog mClosePromptDialog;
    //创建广播
    HomeKeyReceiver homeKeyReceiver = new HomeKeyReceiver();
    //动态注册广播
    IntentFilter intentFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
    private boolean homeKeyCode = false;

    public static void showActivity(Context context, boolean openBluetoothConnect) {
        Intent intent = new Intent(context, MainActivity.class);
        intent.putExtra("openBluetoothConnect", openBluetoothConnect);
        context.startActivity(intent);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void initData() {
        PropertyValuesHolder scaleXHolder = PropertyValuesHolder.ofFloat("scaleX", 1.0f, 0.5f, 1.0f);
        PropertyValuesHolder scaleYHolder = PropertyValuesHolder.ofFloat("scaleY", 1.0f, 0.5f, 1.0f);
        mScaleAnimator = ObjectAnimator.ofPropertyValuesHolder(ivBluetoothState, scaleXHolder, scaleYHolder)
                .setDuration(1750);
        mScaleAnimator.setRepeatMode(ValueAnimator.REVERSE);
        mScaleAnimator.setRepeatCount(ValueAnimator.INFINITE);
        mScaleAnimator.start();

        //button渐变动画
//        ObjectAnimator alpha1 = ObjectAnimator.ofFloat(btnBluetooth, "alpha", 0f, 1f);
        ObjectAnimator alpha2 = ObjectAnimator.ofFloat(btnClock, "alpha", 0f, 1f);
        ObjectAnimator alpha3 = ObjectAnimator.ofFloat(btnLed, "alpha", 0f, 1f);
        AnimatorSet as = new AnimatorSet();
        as.playSequentially(alpha2, alpha3);
        as.setDuration(500);
        as.start();
        mContext = this;
        mClosePromptDialog = new PromptDialog();
        mSearchDialog = new SearchBluetoothDialog();
        mClosePromptDialog = PromptDialog.newInstance(getString(R.string.close_connect_hint),
                getString(R.string.yes),
                getString(R.string.cancel));
//        registerReceiver(homeKeyReceiver, intentFilter);

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        boolean openBluetoothConnect = intent.getBooleanExtra("openBluetoothConnect", false);
        if (openBluetoothConnect) {
            if (!pdlRoot.isOpen()) {
                pdlRoot.toggleBottomView();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        connectedDevice = bluzDeviceUtils.getConnectionDevice();
        registerReceiver(homeKeyReceiver, intentFilter);
        if (connectedDevice == null) {
            isConnect = false;
        } else {
            isConnect = true;
            SpManager.getInstance().saveDeviceAddress(connectedDevice.getAddress());
        }

    }

    @SuppressWarnings({"unused"})
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onBluzManagerReady(BluzManagerReadyEvent event) {
        BluzManagerUtils bluzManagerUtils = BluzManagerUtils.getInstance();
        if (bluzManagerUtils.getBluzManager() != null) {
            DialogFragmentUtils.dismissDialog(getSupportFragmentManager(), BLUETOOTH_SEARCH_DIALOG_TAG);
            ToastUtil.showConnectSuccessToast();
            //弹框
            bluzManagerUtils.setSystemTime();
            isConnect = true;
            SpManager.getInstance().saveMaxVolume(bluzManagerUtils.getMaxVolume());
        }
    }

    /**
     * 蓝牙连接状态改变
     *
     * @param event 事件
     */

    @SuppressWarnings({"unused"})
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onConnectionStateChanged(ConnectedStateChangedEvent event) {
        BluetoothDevice device = event.getBluetoothDevice();
        Log.i("main", "蓝牙连接状态 = " + event.isConnected());
        if (event.isConnected()) {
            Config.isConnected = true;
            mScaleAnimator.end();
            Log.i("main", "停止動畫");
            connectedDevice = device;
            SpManager.getInstance().saveDeviceAddress(device.getAddress());
            mBluzManagerUtils.createBluzManager(bluzDeviceUtils.getBluzDevice());
            Log.i("main", "Device = " + bluzDeviceUtils.getBluzDevice());
            ivPhone.setSelected(true);
            ivBluetoothState.setSelected(true);
            tvBluetoothInfo.setText(getString(R.string.bluetooth_info, device.getName(), device.getAddress()));

            //设置终端设备的系统时间
            Calendar calendar = Calendar.getInstance();

            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH) + 1;
            int day = calendar.get(Calendar.DAY_OF_MONTH);
            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            int minute = calendar.get(Calendar.MINUTE);
            int second = calendar.get(Calendar.SECOND);

            BluzManagerUtils.getInstance().checkTime(year, month, day, hour, minute, second);
            if (disconnectHintDialog!=null){
                disconnectHintDialog.dismiss();
            }
        } else {
            Config.isConnected = false;
            mScaleAnimator.start();
            Log.i("main", "開啓動畫");
            isConnect = false;
            releaseAll();
            DialogFragmentUtils.dismissDialog(getSupportFragmentManager(), DISCONNECT_DIALOG_TAG);
//            MusicCache.getPlayService().pause();
            ivPhone.setSelected(false);
            ivBluetoothState.setSelected(false);
            mScaleAnimator.start();
            tvBluetoothInfo.setText(getString(R.string.bluetooth_info, "______", "_______"));
            if (isUserDisconnect) {
                //如果是用户主动断开，不做处理，只将 isUserDisconnect 赋值为 false
                isUserDisconnect = false;
            } else {
                //如果不是用户主动断开连接，则弹出提示对话框
                if (!homeKeyCode) {
                    showBluetoothDisconnectDialog();
                }
                homeKeyCode = false;
            }

            Log.i("main", "蓝牙已经断开...");
        }
    }

    private void releaseAll() {
        mBluzManagerUtils.setOnGlobalUIChangedListener(null);
        mBluzManagerUtils.release();
        connectedDevice = null;
    }

    @Override
    public void initView() {
        tvBluetoothInfo.setText(getString(R.string.bluetooth_info, "______", "_______"));
        Log.i("index", "oncreate");
    }

    @Override
    public void addViewListener() {
        //蓝牙开关点击
        ivBluetoothState.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                if (isConnect) {
                    mClosePromptDialog.show(getSupportFragmentManager(), DISCONNECT_DIALOG_TAG);
                } else {
                    mSearchDialog.show(getSupportFragmentManager(), BLUETOOTH_SEARCH_DIALOG_TAG);
                }
            }
        });


        pdlRoot.setOnStateListener(new PullUpDragLayout.OnStateListener() {
            @Override
            public void open() {
                ivDrag.setVisibility(View.GONE);
                ivTitle.setVisibility(View.VISIBLE);

            }

            @Override
            public void close() {
                ivDrag.setVisibility(View.VISIBLE);
                ivTitle.setVisibility(View.INVISIBLE);

            }
        });
        mClosePromptDialog.setOnButtonClickListener(new PromptDialog.OnButtonClickListener() {
            @Override
            public void onPositiveClick() {
                isUserDisconnect = true;
                bluzDeviceUtils.disconnect(bluzDeviceUtils.getConnectionDevice());
            }

            @Override
            public void onNegativeClick() {
            }
        });
        // 蓝牙监听
        bluzDeviceUtils.setOnConnectionListener();
    }

    @Override
    protected void onStart() {
        super.onStart();

    }

    /**
     * home键监听
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onHomeKeyListener(HomeKeyEvent event) {
        homeKeyCode = true;
        bluzDeviceUtils.release();
//        releaseAll();
        Log.i("main", "释放蓝牙资源...");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (bluzDeviceUtils.getBluzDevice() == null) {
            bluzDeviceUtils = BluzDeviceUtils.getInstance();
        }
        // 蓝牙监听
        bluzDeviceUtils.setOnConnectionListener();
        Log.i("main", "mBluzManagerUtils.getBluzManager() = " + mBluzManagerUtils.getBluzManager());
        Log.i("main", "onRestart");
    }


    @Override
    public void onBackClick() {

    }


    @OnClick({R.id.btn_bluetooth, R.id.btn_led, R.id.btn_clock})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_bluetooth:
                if (!pdlRoot.isOpen()) {
                    showActivity(MusicActivity.class);
                }
                break;
            case R.id.btn_led:
                if (!pdlRoot.isOpen()) {
                    unregisterReceiver(homeKeyReceiver);
                    showActivity(LedActivity.class);
                }
                break;
            case R.id.btn_clock:
                if (!pdlRoot.isOpen()) {
                    unregisterReceiver(homeKeyReceiver);
                    showActivity(AlarmActivity.class);
                }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.i("index", "on pause");
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mScaleAnimator.cancel();
        mScaleAnimator = null;
        Log.i("index", "onDestroy");
        releaseAll();
        mBluzManagerUtils.release();
        bluzDeviceUtils.release();
        unregisterReceiver(homeKeyReceiver);
    }


}
